from rest_framework.generics import ListAPIView
from . import models
from .serializers import (CourseCategoryModelSerializer, CourseModelSerializer, CourseChapterModelSerializer)


class CourseCategoryAPIView(ListAPIView):
    queryset = models.CourseCategory.objects.filter(is_show=True, is_deleted=False).order_by('orders', '-id')
    serializer_class = CourseCategoryModelSerializer


"""
利用'django-filter'加上过滤以及排序的课程视图接口
"""

# 'django_filters'提供的过滤插件'DjangoFilterBackend'
from django_filters.rest_framework import DjangoFilterBackend

# 'DRF'提供的排序插件'OrderingFilter'
from rest_framework.filters import OrderingFilter

# 分页插件
from luffy.utils.pagination import MyPageNumberPagination


class CourseListAPIView(ListAPIView):
    queryset = models.Course.objects.filter(is_deleted=False, is_show=True).order_by('orders')
    serializer_class = CourseModelSerializer

    filter_backends = [DjangoFilterBackend, OrderingFilter]

    # 按照课程类名进行分类的条件
    filter_fields = ('course_category',)

    # 根据课程的'id'、'students'、'price' 即'id、学习人数、价格'进行排序
    ordering_fields = ('id', 'students', 'price')

    pagination_class = MyPageNumberPagination


# 获取单条数据（根据pk）
from rest_framework.generics import RetrieveAPIView
from .serializers import CourseDedailModelSerializer


class CourseRetrieveAPIView(RetrieveAPIView):
    queryset = models.Course.objects.filter(is_deleted=False, is_show=True).order_by('orders')
    serializer_class = CourseDedailModelSerializer


class CourseChapterAPIView(ListAPIView):
    queryset = models.CourseChapter.objects.filter(is_show=True, is_deleted=False).order_by('orders', 'id')
    serializer_class = CourseChapterModelSerializer
    filter_backends = [DjangoFilterBackend, ]
    filter_fields = ['course']


from django.shortcuts import HttpResponse
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from luffy.libs.polyv.player import PolyvPlayer
from luffy.settings.dev import POLYV_CONFIG


class PolyvAPIView(APIView):
    """
    获取 polyv平台提供的token值
    """
    # 判断是否为本网站的用户（得通过jwt登录认证的）
    permission_classes = [IsAuthenticated, ]

    def get(self, request):
        """
        获取保利威视频播放的 token 值
        :param request:
        :return:
        """
        userId = POLYV_CONFIG['userId']
        secretKey = POLYV_CONFIG['secretKey']
        tokenUrl = POLYV_CONFIG['tokenUrl']
        polyv_obj = PolyvPlayer(userId, secretKey, tokenUrl)

        vid = request.query_params.get('vid')
        viewerIp = request.META.get('REMOTE_ADDR')
        viewerId = request.user.id
        viewerName = request.user.username

        ret = polyv_obj.get_video_token(vid, viewerIp, viewerId, viewerName)

        return HttpResponse(ret.get('token'))
